package com.siemens.industrial.app;

import org.springframework.jdbc.core.JdbcTemplate;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by qupen on 2016/9/22.
 */
public class HeartBeat {
    private static final String findAllGateWayInfo = "select * from `siemens`.gateway_info;";

    public boolean beat() {
        System.out.println("Hello, sql! >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        JdbcTemplate jdbcTemplate = DBHelper.getJdbcTemplate();

        if (jdbcTemplate == null) {
            System.out.println("Get database connection failed.");
            return false;
        }

        List<Map<String, Object>> gateWayList = jdbcTemplate.queryForList(findAllGateWayInfo);

        if (gateWayList == null || gateWayList.size() == 0)
            return false;

        int count;

        if (gateWayList.size() % 2 != 0) {
            count = gateWayList.size() / 2 + 1;
        } else {
            count = gateWayList.size() / 2;
        }

        ExecutorService es = Executors.newFixedThreadPool(count);

        for (Map<String, Object> gatewayInfo : gateWayList) {
            HeartTask pingThread = new HeartTask(gatewayInfo.get("clientId").toString());
            es.execute(pingThread);
        }

        es.shutdown();
        return true;
    }
}
